package com.example.chat.repository

import android.util.Log
import com.example.chat.dao.MessageDao
import com.example.chat.dao.TopicDao
import com.example.chat.model.Message
import com.example.chat.model.MessageStatus
import com.example.chat.model.UserMessage
import com.example.chat.service.MessageService
import com.example.featuresdk.repository.IRepository
import com.example.featuresdk.repository.ReadAsFlow
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class MessageRepository
@Inject constructor(private val messageDao: MessageDao, private val topicDao: TopicDao,
                    private val messageService: MessageService
) : IRepository<Message> {

    suspend fun getUserMessage(vararg params: Any): Flow<List<UserMessage>> {
        val topicId = params[0] as Long
        return ReadAsFlow(
            fetchLocalData = { messageDao.getUserMessage(topicId) },
            shouldFetchRemoteData = { false }
        ).execute()
    }

    override suspend fun get(vararg params: Any): Flow<List<Message>> {

        val topicId = params[0] as Long
        Log.e("MessageRepository", "get message for topicId = $topicId")

        return ReadAsFlow(
            fetchLocalData = { messageDao.get(topicId) },
            shouldFetchRemoteData = { false },
            fetchRemoteData = { messageService.getMessages(topicId) },
            saveRemoteData = { msg -> messageDao.insert(msg) }).execute()
    }

    override suspend fun create(items: List<Message>) {
        messageDao.insert(items)

//        items.last().apply {
//            topicDao.update(this.topicId,this.text?:"",this.timestamp)
//        }
    }

    override suspend fun create(item: Message) {
        this.create(listOf(item))
    }

    suspend fun updateStatus(status: MessageStatus, topicId: Long){
        messageDao.updateStatus(status, topicId)
    }

    override suspend fun create(vararg items: Message) {
        this.create(items.asList())
    }
}